<template>
  <!-- 列表头部模块 -->
  <z-paging ref="paging"
            v-model="dataList"
            @query="queryList"
            :refresher-complete-delay="600"
            :default-page-size="100">
    <template #top>
      <view class="tabs">
        <up-tabs :list="listMenu" @click="click" lineWidth="30" line-height="5"
                 lineColor="#f56c6c"
                 :scrollable="false"
                 :activeStyle="{color: '#FC7649',transform: 'scale(1.05)',fontSize: '27rpx',fontWeight: 'bold'}"
                 :inactiveStyle="{color: '#3D3D3D',transform: 'scale(1)',fontSize: '28rpx'}"
                 itemStyle="padding-left: 15px; padding-right: 15px; height: 50px;"></up-tabs>
      </view>
      <view class="notice_box">
        <u-notice-bar text="温馨提示：支付时请使用系统付款，切勿私自给业务员转账"></u-notice-bar>
      </view>
    </template>
    <!-- 列表底部模块 -->
    <template #bottom>
      <!-- 底部 -->
      <view class="bottom" v-if="currentTabIndex===0">
        <view class="btn_content">
          <view class="btn1" @click="selectAll(allSelectCount === 0)">{{
              allSelectCount === 0 ? '全选' : '取消全选'
            }}({{
              allSelectCount
            }})
          </view>
          <view class="btn2" @click="pay_order">一键支付&nbsp;￥{{ allSelectMoney.toFixed(2) }}</view>
        </view>
        <u-safe-bottom></u-safe-bottom>
      </view>
      <view v-else>
        <u-safe-bottom></u-safe-bottom>
      </view>
    </template>
    <!-- 下拉刷新模块 -->
    <template #refresher>
      <!-- 此处的custom-refresh为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，下拉刷新就显示什么view -->
      <view style="display: flex;justify-content: center;align-items: center;padding-top: 120rpx;">
        <image style="width: 110rpx;height: 110rpx;margin: auto"
               src="https://lsz.lszbg.com/imgs/logo_loading.gif"></image>
      </view>
    </template>
    <!-- 加载中模块 -->
    <template #loading>
      <view style="display: flex;flex-direction: column;align-items: center;padding-top: 120rpx;"
            v-if="!isRefresh">
        <image style="width: 110rpx;height: 110rpx;" src="https://lsz.lszbg.com/imgs/logo_loading.gif"></image>
        <view
            style="font-size: 38rpx;font-weight: 600;color: #F97632;text-align: center;box-sizing: border-box;padding: 40rpx 0;">
          领食周边购
        </view>
      </view>
    </template>
    <!-- 列表项模块 -->
    <view v-for="(items,index) in dataList" v-if="dataList.length > 0" :key="index" class="shops_list">
      <view class="item_root" @click="selectedItem(items)">
        <view style="display: flex;justify-content: flex-start;align-items: center;">
          <view class="dianji" v-if="items.is_pay !== 1">
            <image v-if="items.isSelector" class="check_icon"
                   :src="BaseImgUrl + '/images/select_fill.png'"></image>
            <view v-else class="check_icon"
                  style="background-color: #DEDEDE;border-radius: 300rpx;width: 38rpx;height: 38rpx"></view>
          </view>
          <image class="icon-pic" :src="BaseURL+items.logo"></image>
          <view class="content">
            <view class="title">
              {{ items.shop_name }}
            </view>
            <view class="center">
              <view class="sub_title_label1" v-if="items.shop_type === 1">美团</view>
              <view class="sub_title_label" v-if="items.shop_type === 2">饿了么</view>
              <view class="sub_title_label2" v-if="items.shop_type === 3">京东</view>
              <view class="sub_title">
                完成：{{ items.order_num }}单
              </view>
              <view class="sub_title" @click.stop="toOrderDetail(items)"
                    style="color: #ffa654;margin-left: 10rpx;display: flex;align-items: center">
                <text>账单</text>
                <u-icon name="arrow-right" size="12" color="#ffa654"></u-icon>
              </view>
            </view>
            <view class="sub_title1">
              活动时间：{{ items.date }}{{ items.merge_date ? ('~' + items.merge_date) : '' }}
            </view>
          </view>
          <view class="end_content">
            <view class="end_title" :style="items.is_pay === 0 ? 'color: #F9661C':'color: #2dc197'">
              {{ items.is_pay === 0 ? '待支付' : '已支付' }}
            </view>
            <view style="height: 16rpx;">
            </view>
            <view class="end_title" :style="items.is_pay === 0 ? 'color: #F9661C':'color: #2dc197'">
              {{ items.pay_amount }}元
            </view>
          </view>
        </view>
        <view v-if="items.is_pay !== 0" style="text-align: right;margin-top: 16rpx;font-size: 24rpx;color: #999999">支付时间：{{ items.pay_time }}</view>
      </view>
    </view>
    <!-- 空数据提示模块 -->
    <template #empty>
      <XtxEmpty/>
    </template>
    <!-- 没有更多数据提示模块 -->
    <template #loadingMoreNoMore>
      <view style="font-size: 22rpx;color: #b4b4b4;text-align: center;box-sizing: border-box;padding: 40rpx 0;">
        没有更多数据
      </view>
    </template>
  </z-paging>
  <!-- 支付方式选择弹窗模块 -->
  <u-popup :show="showPay" mode="bottom" radius="10" closeable @close="showPay = false">
    <view class="pay_type">选择支付方式</view>
    <view class="popup_content">
      <!-- 后台控制支付方式 -->
      <view class="pay-way">
        <view class="radio-list">
          <view style="display: flex;flex-direction: column;">
            <view class="radio-one">
              <view class="radio-left" @tap="NewradioChange" :data-type="item.type"
                    v-for="(item, index) in payTypeList" :key="index">
                <image v-if="item.name === '余额支付'" :src="BaseImgUrl + '/images/ye_icon.png'"></image>
                <image v-if="item.name === '微信支付'" :src="BaseImgUrl + '/images/wx_icon.png'"></image>
                <image v-if="item.name === '支付宝支付'" :src="BaseImgUrl + '/images/zfb_icon.png'"></image>
                <view class="radio-int">{{ item.name }}</view>
                <view class="dianji">
                  <image v-if="NewPayType === item.type" class="check_icon"
                         :src="BaseImgUrl + '/images/select_fill.png'"></image>
                  <image v-else class="check_icon" :src="BaseImgUrl + '/images/select_icon.png'"></image>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <button class="submit" @tap="pay">
        立即支付
      </button>
    </view>
  </u-popup>
</template>

<script setup>
import {nextTick, ref} from "vue";
import {onPageScroll, onReachBottom, onShow} from "@dcloudio/uni-app";
import useZPaging from "z-paging/components/z-paging/js/hooks/useZPaging";
import XtxEmpty from "../../components/XtxEmpty.vue";
import {BaseImgUrl, BaseURL} from "../../utils/lshttp";
import {getOfficialAccountInfoAPI, wechatH5AuthLoginAPI, wechatH5LoginAPI} from "../../services/login";
import {aliPayAPI, finishBillListsAPI, payBillListsAPI, wechatPayAPI} from "../../services/buisiness";
import {useUserInfoStore} from "../../stores/modules/userInfo";

const paging = ref(null)
let dataList = ref([])
const allSelectCount = ref(0)
const allSelectMoney = ref(0)
const ids = ref('')
useZPaging(paging)
const useUser = useUserInfoStore() // 使用userInfoStore状态管理器
const showPay = ref(false)
const listMenu = ref([
  {name: '待支付'},
  {name: '已完成'}
]);
const currentTabIndex = ref(0)

function click(item) {
  console.log('item', item);
  currentTabIndex.value = item.index
  paging?.value?.refresh()
}

const payTypeList = ref([
  {
    name: '微信支付',
    type: 'wechat',
  },
  {
    name: '支付宝支付',
    type: 'app_alipay',
  }
])

const selectAll = (isSelectedAll) => {
  if (!isSelectedAll) {
    allSelectMoney.value = 0
    allSelectCount.value = 0
  } else {
    allSelectCount.value = dataList.value.length
  }
  dataList.value.forEach((item) => {
    if (!isSelectedAll) {
      item.isSelector = false
      ids.value = ''
    } else {
      allSelectMoney.value = allSelectMoney.value + parseFloat(item.pay_amount)
      item.isSelector = true
      ids.value = ids.value + (ids.value ? ',' : '') + item.bill_id
    }
  })
}
const selectedItem = (item) => {
  item.isSelector = !item.isSelector
  if (item.isSelector) {
    allSelectCount.value = allSelectCount.value + 1
    allSelectMoney.value = allSelectMoney.value + parseFloat(item.pay_amount)
  } else {
    allSelectCount.value = allSelectCount.value - 1
    allSelectMoney.value = allSelectMoney.value - parseFloat(item.pay_amount)
  }
}
const queryList = (pageNo, pageSize) => {
  allSelectMoney.value = 0
  allSelectCount.value = 0
  let billIds = [];
  if (ids.value) {
    billIds = ids.value.split(',')
  }

  if (currentTabIndex.value === 0) {
    payBillListsAPI({
      limit: pageSize,
      page: pageNo,
      shop_id: shopID.value
    }).then(res => {
      if (res.result.length > 0 && billIds.length > 0) {
        res.result.forEach((item) => {
          for (let i = 0; i < billIds.length; i++) {
            if (item.bill_id === parseInt(billIds[i])) {
              item.isSelector = true
              allSelectCount.value = allSelectCount.value + 1
              allSelectMoney.value = allSelectMoney.value + parseFloat(item.pay_amount)
              break;
            }
          }
        })
      }
      paging?.value.complete(res.result);
    }).catch(() => {
      paging?.value.complete(false);
    })
    return
  }
  finishBillListsAPI({
    limit: pageSize,
    page: pageNo,
    shop_id: shopID.value
  }).then(res => {
    if (res.result.length > 0 && billIds.length > 0) {
      res.result.forEach((item) => {
        for (let i = 0; i < billIds.length; i++) {
          if (item.bill_id === parseInt(billIds[i])) {
            item.isSelector = true
            allSelectCount.value = allSelectCount.value + 1
            allSelectMoney.value = allSelectMoney.value + parseFloat(item.pay_amount)
            break;
          }
        }
      })
    }
    paging?.value.complete(res.result);
  }).catch(() => {
    paging?.value.complete(false);
  })
}
const toOrderDetail = (item) => {
  // if (authWX()) {
  uni.navigateTo({url: '/pages/business_order/order_detail?bill_id=' + item.bill_id + '&shopId=' + shopID.value + "&h5WxCode=" + h5WxCode.value})
  // }
}
onPageScroll(e => {

})

onReachBottom(() => {

})
const NewPayType = ref('wechat')
const NewradioChange = (evt) => {
  NewPayType.value = evt.currentTarget.dataset.type
}
const pay_order = () => {
  if (allSelectMoney.value === 0) {
    uni.showToast({title: '请选择账单', icon: 'none'})
    return
  }
  showPay.value = true
}
const pay = async () => {
  ids.value = ''
  dataList.value.forEach((item) => {
    if (item.isSelector) {
      ids.value = ids.value + (ids.value ? ',' : '') + item.bill_id
    }
  })
  showPay.value = false
  // 支付宝支付
  if (NewPayType.value === 'app_alipay') {
    const returnUrl = BaseURL + '/business/index.html#/pages/business_order/order_alipay?shopId=' + shopID.value
    const res = await aliPayAPI({ids: ids.value, return_url: returnUrl})
    useUser.setPayForm(res.result[0])
    // console.log("app_alipay", res.result[0])
    // await uni.navigateTo({url: '/pages/business_order/order_alipay'})
    document.querySelector('body').innerHTML = res.result[0].split("<script>")[0];
    await nextTick(() => {
      window.document.forms[0].submit()
    })
    return
  }


  // 微信支付
  if (!useUser.openID) {
    if(!h5WxCode.value){
      await uni.showToast({title: "正在微信授权", icon: "none", duration: 2000})
      setTimeout( () => {
        authWX()
      }, 1000)
      return
    }
  }
  // 微信支付接口
  wechatPayAPI({ids: ids.value, code: h5WxCode.value, openid: useUser.openID}).then(res => {
    //是否重复授权
    useUser.setOpenID(res.result.openid)
    console.log("useUser.openID", useUser.openID)
    console.log("wechatPayAPI1--->>>", res)

    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          appId: res.result.appId,
          timeStamp: res.result.timeStamp,
          nonceStr: res.result.nonceStr,
          package: res.result.package,
          signType: res.result.signType,
          paySign: res.result.paySign,
        },
        function (res1) {
          if (res1.err_msg == "get_brand_wcpay_request:ok") {
            uni.showToast({
              title: '支付成功',
              icon: 'none',
              success: function () {
                setTimeout(function () {
                  uni.switchTab({
                    url: '/pages/my/my'
                  });
                }, 1800);
              }
            });
          } else {
            uni.showToast({
              title: "取消支付",
              icon: 'none',
            });
          }
        });
  }).catch( async (res) => {
    if (res.data.status === 3) {
      console.log("wechatPayAPI2--->>>", res)
      uni.showToast({title: res.data.msg, icon: 'none'})
      // useUser.clearOpenID();
      // h5WxCode.value = ''
      // authWX()
    }
  })
}

const shopID = ref()
onShow(async () => {
  paging?.value?.refresh();
  shopID.value = getUrlParam("shopId")
  h5WxCode.value = getUrlParam("code");

  /* uni.showModal({
    title: '提示',
    content: "ids=" + ids.value + "h5WxCode=" + h5WxCode.value + "openID=" + useUser.openID,
    confirmText: '获取code',
    success: async function (res) {
      if (res.confirm) {
        // 封装授权登录函数
        // await useUser.authLogin(0, h5WxCode.value)
        // await wechatH5LoginFun(h5WxCode.value)
      }
    }
  }) */
})
const h5WxCode = ref()
// 重新授权
const authWX = async () => {
  let code = getUrlParam("code"); //是否存在code 截取code代码 授权会返回code需要截取链接中code
  if (code == null || code === '' || h5WxCode.value === '') {
    const res = await getOfficialAccountInfoAPI();
    /* uni.showModal({
      title: '提示',
      content: res.result.appid + "," + h5WxCode.value + "," + code,
      confirmText: '获取openid',
      success: async function (res) {
        if (res.confirm) {
          // 封装授权登录函数
          // await useUser.authLogin(0, h5WxCode.value)
          // await wechatH5LoginFun(h5WxCode.value)
        }
      }
    }) */
    let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + res.result.appid + '&redirect_uri=' +
        encodeURIComponent(BaseURL + '/business/index.html#/pages/business_order/order_list?shopId=') + shopID.value +
        '&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect';
    window.location.replace(url);
    return
  }

  h5WxCode.value = getUrlParam("code");
}

// 公众号截取code
const getUrlParam = (name) => {
  // #ifdef H5
  // 判断公众号截取code
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [undefined,
    ''
  ])[1].replace(/\+/g, '%20')) || null
  // #endif
}
</script>
<style>
page {
  background-color: #F6F6F6;
}
</style>
<style lang="scss" scoped>
.dianji {
  margin-left: auto;

  image {
    width: 36rpx !important;
    height: 36rpx !important;
  }
}

.notice_box {
  //background-color: #FFFBEE;
  display: flex;
  box-sizing: border-box;
  padding: 0 0 10rpx 0;
  //margin-bottom: 20rpx;

  image {
    width: 38rpx;
    height: 38rpx;
    margin-right: 10rpx;
  }

  .desc_text {
    flex: 1;
    display: inline-block;
    font-size: 24rpx;
    color: #EF481B;
    line-height: 45rpx;
  }
}

.item_root {
  background-color: white;
  margin: 0 20rpx 20rpx;
  padding: 16rpx 16rpx;
  border-radius: 10rpx;

  .content {
    flex: 1;
    margin-left: 10rpx;


    .sub_title1 {
      margin-top: 10rpx;
      font-size: 20rpx;
      color: #666666;
    }

    .center {
      display: flex;
      align-items: center;
      margin: 6rpx 0;

      .sub_title_label {
        font-size: 20rpx;
        color: white;
        width: 78rpx;
        text-align: center;
        background-color: #1db9ff;
        padding: 4rpx 0;
        border-radius: 60rpx;
        margin-right: 10rpx;
      }

      .sub_title_label1 {
        font-size: 20rpx;
        color: #333333;
        width: 68rpx;
        text-align: center;
        background-color: #FECC32;
        padding: 4rpx 0;
        border-radius: 60rpx;
        margin-right: 10rpx;
      }

      .sub_title_label2 {
        font-size: 20rpx;
        color: #FFFFFF;
        width: 68rpx;
        text-align: center;
        background-color: #db2727;
        padding: 4rpx 0;
        border-radius: 60rpx;
        margin-right: 10rpx;
      }
      .sub_title {
        font-size: 22rpx;
        color: #F9661C;
      }
    }
  }

  .title {
    font-size: 26rpx;
    font-weight: bold;
    color: black;
    min-height: 60rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .icon-pic {
    width: 148rpx;
    height: 148rpx;
    margin: 0 10rpx;
    border-radius: 16rpx;
  }

  .end_content {
    font-size: 28rpx;
    color: #F9661C;
    min-width: 100rpx;
    margin-left: 2rpx;
    text-align: center;

    .end_title {
      margin: auto;
      font-weight: bold;
    }
  }
}

.bottom {
  background-color: white;
  padding: 16rpx 20rpx;

  .btn_content {
    display: flex;
    font-size: 32rpx;

    .btn1 {
      border-radius: 300rpx;
      border: #666666 solid 1rpx;
      color: black;
      text-align: center;
      padding: 16rpx 60rpx;
    }

    .btn2 {
      border-radius: 300rpx;
      margin-left: 20rpx;
      color: white;
      padding: 16rpx 10rpx;
      flex: 1;
      text-align: center;
      background: linear-gradient(270deg, #FEB85A 0%, #FC754A 100%);
    }
  }
}

/* 支付 */
.pay_type {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  text-align: center;
  margin-top: 20rpx;
}

.popup_content {
  box-sizing: border-box;
  padding-bottom: 50rpx;
}

.pay-way {
  margin-top: 20rpx;
  padding: 10rpx 30rpx;
  background-color: #FFFFFF;
  border-radius: 40rpx;
}

.radio-list {
  background-color: #FFFFFF;
}

.radio-one {
  //display: flex;
  //align-items: center;
  //justify-content: space-between;
  //margin: 30rpx 0;
}

.radio-left {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 26rpx 0;
  border-top: #EAEAEA solid 1rpx;
}

.radio-left image {
  width: 58rpx;
  height: 58rpx;
  display: inline-block;
}

.radio-int {
  font-size: 26rpx;
  margin-left: 20rpx;
}

.check_icon {
  width: 34rpx;
  height: 34rpx;
  position: relative;
  top: 0;
  margin-right: 7rpx;
}

.dianji {
  margin-left: auto;

  image {
    width: 38rpx !important;
    height: 38rpx !important;
    opacity: .9;
  }
}

.submit {
  margin: 0 20rpx;
  font-weight: bold;
  height: 100rpx;
  background: linear-gradient(270deg, #FEB85A 0%, #FC754A 100%);
  border-radius: 60rpx;
  font-size: 36rpx;
  color: white;
  line-height: 100rpx;
}

.submit text {
  font-size: 48rpx;
  color: #ff5339;
}

.tabs {
  padding: 0 10rpx;
  background-color: #FFFFFF;
  //box-shadow: #F6F6F6 0 2rpx 8rpx 2rpx;
}
</style>
